var allPro = null;
var allBase = null;
var work_type = null;
var lastsel;
$(function () {
    $.when(
        $.get(baseURL + 'bss/dpoint/select?pGuid='+ GetUrlParam("guid"), function (r) {
            allPro = r.returnlist;
        }),
        $.get(baseURL + 'bss/apbase/select?ourid=isok', function (r) {
            allBase = r.returnlist;
        }),
        getdatadictionary("work_type")



    ).done(
    $("#jqGrid").jqGrid({
        url: baseURL + 'bss/dmaterialcost/list?pGuid='+GetUrlParam("pGuid"),
        datatype: "json",
        colModel: [			
			{ label: 'guid', name: 'guid', index: 'guid', width: 50, key: true,hidden:true },
			{hidden:true, label: '所属项目ID', name: 'pGuid', index: 'p_guid', width: 80,
                formatter: function (cellvalue, options, rowObject) {
                    for (d in allBase) {
                        if (cellvalue == allBase[d].guid) return allBase[d].pBName;
                    }
                }
			},
			{ label: '安装位置', name: 'pPGuid', index: 'p_p_guid', width: 80,
                formatter: function (cellvalue, options, rowObject) {
                    for (d in allPro) {
                        if (cellvalue == allPro[d].guid) return allPro[d].pPCode;
                    }
                }
			},
			// { label: '材料购置表id', name: 'pMGuid', index: 'p_m_guid', width: 80 },
			// { label: '材料ID', name: 'mMGuid', index: 'm_m_guid', width: 80 },
            { label: '名称', name: 'mMName', index: 'm_m_name', width: 80 },
			{ label: '工程量类别', name: 'mCWork', index: 'm_c_work', width: 80,
             formatter: function (cellvalue, options, rowObject) {
                for (d in work_type) {
                    if (cellvalue == work_type[d].dKey) return work_type[d].dValue;
                }
                 }
            },
			{ label: '工程量名称', name: 'mCQuantities', index: 'm_c_quantities', width: 150 },
			{ label: '工程量说明', name: 'mCExplain', index: 'm_c_explain', width: 80 }, 			
			{ label: '购置单位', name: 'mCUnit', index: 'm_c_unit', width: 80 }, 			
			{ label: '计价单位', name: 'mCMeterUnit', index: 'm_c_meter_unit', width: 80 },
			{ label: '现场采集数量', name: 'mCCount', index: 'm_c_count', width: 80},
			{ label: '单价（元）', name: 'mCPrice', index: 'm_c_price', width: 80,
                editable: true,
                editrules: { required: true, number: true, custom: true, custom_func: ValidateTvalue },
                edittype: "text"
			},
			{ label: '合价（元）', name: 'mCPriceall', index: 'm_c_priceall', width: 80,
                formatter:'number', formatoptions:{decimalPlaces: 3}
			},
			{ label: '计量与计价比值', name: 'mCRatio', index: 'm_c_ratio', width: 80 }, 			
			{hidden:true, label: '数据状态', name: 'mCDatastate', index: 'm_c_datastate', width: 80 }
        ],
		viewrecords: true,
        height: 385,
        rowNum: 10,
		rowList : [10,30,50],
        rownumbers: true, 
        rownumWidth: 25, 
        autowidth:true,
        // multiselect: true,
        footerrow:true,
        onSelectRow :EditSelectRow,

        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames : {
            page:"page", 
            rows:"limit", 
            order: "order"
        },
        gridComplete:function(){
            var sum_Fy=$("#jqGrid").getCol('mCCount',false,'sum');
            var sum_qntqFy=$("#jqGrid").getCol('mCPriceall',false,'sum');
            $("#jqGrid").footerData('set', {  'mCCount': sum_Fy.toFixed(3), 'mCPriceall': sum_qntqFy.toFixed(3) });
            //隐藏grid底部滚动条
            $("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });
        }
    })
	)
});

function getdatadictionary(sss)
{

    $.get(baseURL + "api/bdatadictionary/select?d_code="+sss, function(r){
        if(sss=="work_type")
        {
            work_type=r.returnlist;
        }

        vm.work_type=work_type;
    });
}

//选中行启用行编辑
var selectRowId=""
function EditSelectRow(id)
{
    //原选中行ID
    var oldSelectRowId = selectRowId;
    if (oldSelectRowId != null && oldSelectRowId != "" && oldSelectRowId.length > 0) {
        // $("#jqGrid").jqGrid('saveRow', oldSelectRowId);

        $('#jqGrid').jqGrid('saveRow',oldSelectRowId,{

            keys : true,		//这里按[enter]保存
            url: baseURL  + "bss/dmaterialcost/updateCell",
            mtype : "POST",
            restoreAfterError: true,
            extraparam: {

            },
            oneditfunc: function(oldSelectRowId){
                console.log(1111);
            },
            aftersavefunc: function(oldSelectRowId) {
                var strValue1=$("#jqGrid").jqGrid("getCell",oldSelectRowId,"mCCount");
                var strValue2=$("#jqGrid").jqGrid("getCell",oldSelectRowId,"mCPrice");
                jQuery("#jqGrid").jqGrid("setRowData", oldSelectRowId, { 'mCPriceall': strValue1* strValue2});
                var sum_Fy=$("#jqGrid").getCol('mCCount',false,'sum');
                var sum_qntqFy=$("#jqGrid").getCol('mCPriceall',false,'sum');
                $("#jqGrid").footerData('set', {  'mCCount': sum_Fy.toFixed(3), 'mCPriceall': sum_qntqFy.toFixed(3) });

            },
            succesfunc: function(response){
                console.log(33333);
                return true;
            },
            errorfunc: function(oldSelectRowId, res){
                console.log(222);

            }
        });

    }

    //当前选中行
    selectRowId=id;//临时存储当前选中行
    //$("#fieldGrid").jqGrid('editRow', id);


    $('#jqGrid').jqGrid('editRow',id,{

        keys : true,		//这里按[enter]保存
        url: baseURL  + "bss/dmaterialcost/updateCell",
        mtype : "POST",
        restoreAfterError: true,
        extraparam: {

        },
        oneditfunc: function(id){
            console.log(1111);
        },
        aftersavefunc: function(id) {
            var strValue1=$("#jqGrid").jqGrid("getCell",id,"mCCount");
            var strValue2=$("#jqGrid").jqGrid("getCell",id,"mCPrice");
            jQuery("#jqGrid").jqGrid("setRowData", id, { 'mCPriceall': strValue1* strValue2});
            var sum_Fy=$("#jqGrid").getCol('mCCount',false,'sum');
            var sum_qntqFy=$("#jqGrid").getCol('mCPriceall',false,'sum');
            $("#jqGrid").footerData('set', {  'mCCount': sum_Fy.toFixed(3), 'mCPriceall': sum_qntqFy.toFixed(3) });

        },
        succesfunc: function(response){
            console.log(33333);
            return true;
        },
        errorfunc: function(id, res){
            console.log(222);

        }
    });


}

var vm = new Vue({
	el:'#rrapp',
	data:{
		showList: true,
		title: null,
        q:{
            qName:null,
            qWork:null
        },
        work_type:null,
		dMaterialCost: {}
	},
	methods: {
		query: function () {
			vm.reload();
		},
		add: function(){
			vm.showList = false;
			vm.title = "新增";
			vm.dMaterialCost = {};
		},
		update: function (event) {
			var guid = getSelectedRow();
			if(guid == null){
				return ;
			}
			vm.showList = false;
            vm.title = "修改";
            
            vm.getInfo(guid)
		},
		saveOrUpdate: function (event) {
			var url = vm.dMaterialCost.guid == null ? "bss/dmaterialcost/save" : "bss/dmaterialcost/update";
			$.ajax({
				type: "POST",
			    url: baseURL + url,
                contentType: "application/json",
			    data: JSON.stringify(vm.dMaterialCost),
			    success: function(r){
			    	if(r.code === 0){
						alert('操作成功', function(index){
							vm.reload();
						});
					}else{
						alert(r.msg);
					}
				}
			});
		},
		del: function (event) {
			var guids = getSelectedRows();
			if(guids == null){
				return ;
			}
			
			confirm('确定要删除选中的记录？', function(){
				$.ajax({
					type: "POST",
				    url: baseURL + "bss/dmaterialcost/delete",
                    contentType: "application/json",
				    data: JSON.stringify(guids),
				    success: function(r){
						if(r.code == 0){
							alert('操作成功', function(index){
								$("#jqGrid").trigger("reloadGrid");
							});
						}else{
							alert(r.msg);
						}
					}
				});
			});
		},
		getInfo: function(guid){
			$.get(baseURL + "bss/dmaterialcost/info/"+guid, function(r){
                vm.dMaterialCost = r.dMaterialCost;
            });
		},
		reload: function (event) {
			vm.showList = true;
			var page = $("#jqGrid").jqGrid('getGridParam','page');
			$("#jqGrid").jqGrid('setGridParam',{
                postData:{
                    'qWork': vm.q.qWork,
                    'qName': vm.q.qName,
                },
                page:page
            }).trigger("reloadGrid");
		}
	}
});